<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="title"
    width="600"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="60"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="21">
          <el-form-item label="国家区域名称" prop="country_area_name">
            <el-input
              v-model.trim="form.country_area_name"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="3" class="mt-7">
          <el-form-item label="" label-width="0" prop="status">
            <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="国家" prop="country_list">
        <SelectCountry
          class="w-full"
          v-model="form.country_list"
          multiple
        ></SelectCountry>
      </el-form-item>
      <el-form-item label="头程海运" prop="sea_transport_bulk">
        <VGroup>
          <el-input class="mr-2" v-model="form.sea_transport_bulk" placeholder="货柜体积">
            <template #append>m3</template>
          </el-input>
          <el-input v-model="form.sea_transport_price" placeholder="货柜报价">
            <template #append>CNY</template>
          </el-input>
        </VGroup>
      </el-form-item>
      <el-form-item label="头程空运" prop="air_transport_price">
        <el-input v-model="form.air_transport_price" placeholder="请输入">
          <template #append>CNY</template>
        </el-input>
      </el-form-item>
      <el-form-item label="进口税费比例" prop="import_duty_radio">
        <el-input v-model="form.import_duty_radio" placeholder="请输入">
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="comment">
        <el-input
          v-model.trim="form.comment"
          min-height="200"
          type="textarea"
          placeholder="请输入"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import {
  createBaseHeadFreight,
  updateBaseHeadFreight,
  baseHeadFreightDetail,
} from "../api";
import { reactive, toRefs, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { whetherOptions } from "../data.js";
import SelectCountry from "@/components/SelectCountry";

const { proxy } = getCurrentInstance();
const emits = defineEmits(["query"]);
const data = reactive({
  form: {
    status: 1,
  },
  visible: false,
  loading: false,
  formRef: null,
  rules: {
    // Existing rules
    country_area_name: [
      { required: true, message: "请输入国家区域名称", trigger: "blur" },
    ],
    country_list: [
      {
        required: true,
        message: "请选择国家",
        trigger: "change",
        validator: (rule, value) => {
          return Array.isArray(value) && value.length > 0;
        },
      },
    ],
    // Enhanced and added rules
    sea_transport_bulk: [
      {
        required: true,
        message: "请输入头程海运货柜体积",
        trigger: "blur",
      },
      {
        validator: (rule, value, callback) => {
          if (value && !form.value.sea_transport_price) {
            callback(new Error("请输入头程海运货柜体积"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    air_transport_price: [
      { required: true, message: "请输入头程空运报价", trigger: "blur" },
      { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的金额", trigger: "blur" }, // Allows decimal numbers for price
    ],
    import_duty_radio: [
      { required: true, message: "请输入进口税费比例", trigger: "blur" },
      { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的百分比数值", trigger: "blur" }, // Ensures it's a percentage
    ],
  },
  title: "",
  handleType: "",
  load: false,
});
const { rules, form, visible, loading, formRef, title, handleType, load } = toRefs(data);

const statusMap = new Map([
  ["add", "新增"],
  ["edit", "编辑"],
  ["view", "查看"],
]);

const open = async (type, id) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  title.value = statusMap.get(type);
  handleType.value = type;
  visible.value = true;
  if (id) getDetail(id);
};

const getDetail = (id) => {
  baseHeadFreightDetail({ id }).then((res) => {
    form.value = res.data;
  });
};

const initForm = () => {
  form.value = {
    status: 1,
  };
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      if (form.value.id) {
        updateBaseHeadFreight(form.value)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        createBaseHeadFreight(form.value)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};
const close = () => {
  initForm();
  visible.value = false;
};
defineExpose({ open });
</script>
